package de.akabahn.ebd.comm;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Utility class
 * 
 * @author Peter Eimann
 * @since 0.2
 * @version 0.2
 */
public final class Util {

	private Util() {
	}

	/**
	 * Calls <code>Thread.sleep(millis)</code> but handles the
	 * <code>InterruptedException</code>.
	 * 
	 * @param millis
	 *            The time to sleep in milliseconds
	 */
	public static void sleep(int millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
		}
	}

	/**
	 * Wait for the passed <code>CountDownLatch</code> to finish, catching the
	 * annoying <code>InterruptedException</code>.
	 * 
	 * @param latch
	 *            The countdown latch
	 * @param timeout
	 *            The timeout in ms
	 * @return <code>true</code> if the count reached zero and
	 *         <code>false</code> if the waiting time elapsed before the count
	 *         reached zero
	 */
	public static boolean waitForLatch(CountDownLatch latch, int timeout) {
		try {
			return latch.await(timeout, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
		}

		return false;
	}

	/**
	 * Assert that the passed parameter is not null and not empty.
	 * 
	 * @param param
	 *            The parameter to check
	 * @param name
	 *            The name of the parameter
	 * @throws IllegalArgumentException
	 *             thrown if the parameter is not valid
	 */
	public static void assertNotNullAndEmpty(String param, String name) {
		if (param == null) {
			throw new IllegalArgumentException(name + " must not be null");
		}
		if ("".equals(param.trim())) {
			throw new IllegalArgumentException(name + " must not be empty");
		}
	}

	/**
	 * Assert that the passed parameter is not null.
	 * 
	 * @param param
	 *            The parameter to check
	 * @param name
	 *            The name of the parameter
	 * @throws IllegalArgumentException
	 *             thrown if the parameter is not valid
	 */
	public static void assertNotNull(Object param, String name) {
		if (param == null) {
			throw new IllegalArgumentException(name + " must not be null");
		}
	}

	/**
	 * Assert that the passed parameter is in the range between <code>min</code>
	 * and <code>max</code>.
	 * 
	 * @param param
	 *            The parameter to check
	 * @param name
	 *            The name of the parameter
	 * @param min
	 *            The minimum value
	 * @param max
	 *            The maximum value
	 * @throws IllegalArgumentException
	 *             thrown if the parameter is not valid
	 */
	public static void assertInRange(int param, String name, int min, int max) {
		if ((param < min) || (param > max)) {
			throw new IllegalArgumentException(name + " must be between " + min + " and " + max);
		}
	}
}
